<template>
  <div class="research-center-payment">
    <!-- <a-descriptions class="line" :title="$t('all.autotext1247')" v-if="from!=='high'"></a-descriptions> -->
    <div class="content">
      <!-- <div class="center-list" :class="[centerListEmpty && 'empty']" v-if="from!=='high'">
        <a-input-search
          v-model="searchCenterKey"
          :placeholder="$t('all.autotext848')"
          @search="filterCenterList"
          allowClear
        >
        </a-input-search>
        <template v-if="centerListEmpty">
          <a-empty></a-empty>
        </template>
        <template v-else>
          <div
            :class="['list-item', currentCenterData.resId === item.resId && 'active']"
            v-for="item in researchCenterList"
            :key="item.resId"
            @click="switchResearchCenter(item)"
          >
            <div class="item-title">
              <span class="title-name">{{ item.orgName }}</span>
              <span class="title-amount">¥{{ item.totalAmount | formatAmount }}</span>
            </div>
            <div class="item-id">{{ item.researchCenterNo }}</div>
          </div>
        </template>
      </div> -->
      <div class="center-chart">
        <a-form :labelCol="{span: 7}" :wrapperCol="{span: 16}" :model="queryParam">
          <a-row>
            <!-- 研究中心 -->
            <a-col :span="4">
              <a-form-item :label="$t('all.autotext949')">
                <a-select
                  v-model="queryParam.searchCenterKey"
                  allowClear
                  :placeholder="$t('all.autotext1348')"
                  option-filter-prop="children"
                  show-search
                  filter
                >
                  <a-select-option v-for="item in allCenterList" :key="item.id" :value="item.id">
                    <a-tooltip :title="item.researchCenterNo + '-' + item.orgName">
                      {{ item.researchCenterNo }}-{{ item.orgName }}
                    </a-tooltip>
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <!-- 费用类型 -->
            <a-col :span="4">
              <a-form-item :label="$t('all.autotext765')">
                <a-select v-model="queryParam.type" allowClear>
                  <template v-for="item in $const.SUBJECTANDREESA">
                    <a-select-option :value="item.value" :key="item.value" v-if="$auth(`PROJECT_BOARD.${item.auth}`)">
                      {{ item.desc }}
                    </a-select-option>
                  </template>
                </a-select>
              </a-form-item>
            </a-col>
            <!-- 数据日期 -->
            <a-col :span="4">
              <a-form-item :label="$t('all.autotext655')">
                <a-range-picker
                  style="width: 100%"
                  format="YYYY-MM-DD"
                  :show-time="false"
                  :disabled="!disabledDate"
                  :disabledDate="disabledDate"
                  v-model="queryParam.date"
                />
              </a-form-item>
            </a-col>
            <!-- 访视阶段 -->
            <a-col :span="4" v-if="queryParam.type===2">
              <a-form-item :label="$t('all.autotext1049')">
                <a-select v-model="queryParam.stageId" allowClear @change="listVisitStageChange">
                  <a-select-option v-for="item in listVisitStageOption" :value="item.stageId" :key="item.stageId">
                    {{ item.visitName }}:{{ item.stage }}
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <!-- 费用类目 -->
            <a-col :span="4">
              <a-form-item :label="$t('all.autotext789')">
                <a-select
                  v-model="queryParam.applyType"
                  allowClear
                  :disabled="!queryParam.searchCenterKey || !queryParam.type"
                >
                  <a-select-option v-for="item in categoryOptions" :value="item" :key="item">
                    {{ item }}
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :span="4">
              <a-space style="paddingTop: 4px">
                <a-button :disabled="!disabledDate" @click="handleReset">{{ $t('all.autotext340') }}</a-button>
                <a-button :disabled="!disabledDate" type="primary" @click="getCenterDashboardData">{{ $t('all.autotext30') }}</a-button>
              </a-space>
            </a-col>
          </a-row>
        </a-form>
        <div class="date-range-select">
          <span>{{ $t('all.autotext586') }}：</span>
          <a-radio-group :value="dateFormatType" :disabled="!disabledDate" @change="handleDateRangeChange">
            <a-radio-button :value="1">{{ $t('all.autotext264') }}</a-radio-button>
            <a-radio-button :value="2">{{ $t('all.autotext318') }}</a-radio-button>
            <a-radio-button :value="3">{{ $t('all.autotext1463') }}</a-radio-button>
          </a-radio-group>
        </div>
        <ChartBarLine :data="dashboardData"></ChartBarLine>
      </div>
    </div>
  </div>
</template>

<script>
import ChartBarLine from './chart-bar-line.vue'
import { apiGetCenterDateRestriction, apiGetResearchCenterList, apiGetCenterDashboardData, listFeeCategory } from '@api/dashboard/dashboard'
import { mapGetters } from 'vuex'
import { COMMON_ROLE_TYPE } from '@/constants/common'
import moment from 'moment'
export default {
  name: 'research-center-payment',
  components: { ChartBarLine },
  props: ['from', 'allCenterList', 'listVisitStageOption'],
  data () {
    // 之前的费用类型
    let expenseTypeOptions = []
    if (this.$auth('PROJECT_BOARD.PAY_SITUATION_PATIENT')) {
      expenseTypeOptions.push(
        { value: COMMON_ROLE_TYPE.TESTEE.value, label: COMMON_ROLE_TYPE.TESTEE.desc }
      )
    }
    if (this.$auth('PROJECT_BOARD.PAY_SITUATION_RESEARCHER')) {
      expenseTypeOptions.push(
        { value: COMMON_ROLE_TYPE.RESEARCHER.value, label: COMMON_ROLE_TYPE.RESEARCHER.desc }
      )
    }
    const initQueryParamType = expenseTypeOptions[0]?.value || ''
    return {
      searchCenterKey: '',
      queryParam: {
        searchCenterKey: '',
        type: initQueryParamType,
        date: [],
        stageId: '',
        applyType: ''
      },
      expenseTypeOptions,
      currentCenterData: {},
      allResearchCenterList: [],
      researchCenterList: [],
      disabledDate: null,
      dateFormatType: 2, // 时间跨度： 1-天 2-月 3-年
      dashboardData: {},
      initialQueryDate: [],
      categoryOptions: []
    }
  },
  computed: {
    ...mapGetters({
      project: 'project'
    }),
    centerListEmpty () {
      return this.researchCenterList.length === 0
    },
    proId () {
      // return this.project?.id || ''
      return localStorage.getItem('CURRENT_PROID') || ''
    }
  },
  async created () {
    await this.getDisableDate()
    this.getResearchCenterList()
    if (this.queryParam.date.length) {
      this.getCenterDashboardData()
    }
  },
  methods: {
    // 获取费用类目
    async listFeeCategory () {
      if (!this.queryParam.type || !this.queryParam.stageId) {
        return false
      }
      const res = await listFeeCategory({ proId: this.proId, type: this.queryParam.type, stageId: this.queryParam.stageId })
      console.log('listFeeCategory', res)
      this.categoryOptions = res
    },
    // 费用类目
    listVisitStageChange () {
      this.$set(this.queryParam, 'applyType', '')
      this.listFeeCategory()
    },
    /**
     * 获取左侧研究中心列表
     * @param {Event} e
     * @return {AxiosPromise}
     */
    getResearchCenterList () {
      const { date } = this.queryParam
      const params = {
        proId: this.proId,
        startTime: this.formatDate(date[0]),
        endTime: this.formatDate(date?.[1])
      }
      return apiGetResearchCenterList(params).then(res => {
        this.allResearchCenterList = res
        this.researchCenterList = res
      })
    },
    filterCenterList (value) {
      this.researchCenterList = this.allResearchCenterList.filter(e => {
        return e.orgName?.includes(value) || e.researchCenterNo?.includes(value)
      })
    },
    formatDate (date) {
      return moment(date).format('YYYY-MM-DD')
    },
    getDisableDate () {
      const params = {
        proId: this.proId,
        resId: this.currentCenterData?.resId
      }
      return apiGetCenterDateRestriction(params).then(res => {
        const { startTime, endTime } = res || {}
        if (!(startTime && endTime)) {
          this.queryParam.data = []
          return
        }
        this.queryParam.date = [
          moment(this.formatDate(startTime), 'YYYY-MM-DD'),
          moment(this.formatDate(endTime), 'YYYY-MM-DD')
        ]
        this.initialQueryDate = [...this.queryParam.date]
        this.disabledDate = (current) => {
          return current > endTime || current < startTime
        }
      })
    },
    async switchResearchCenter (data) {
      this.currentCenterData = data
      await this.getDisableDate()
      this.getCenterDashboardData()
    },
    handleReset () {
      this.queryParam = this.$options.data.call(this).queryParam
      this.queryParam.date = [...this.initialQueryDate]
      this.getCenterDashboardData()
    },
    handleDateRangeChange (e) {
      this.dateFormatType = e.target.value
      this.getCenterDashboardData()
    },
    getCenterDashboardData () {
      const { date, type, stageId, applyType, searchCenterKey } = this.queryParam
      if (!date[0]) {
        this.dashboardData = {}
        this.$message.warning(this.$t('all.autotext1339'))
        return
      }
      const params = {
        proId: this.proId,
        resId: searchCenterKey,
        startTime: this.formatDate(date[0]),
        endTime: this.formatDate(date?.[1]),
        type: type,
        dateFormatType: this.dateFormatType,
        stageId,
        applyType
      }
      return apiGetCenterDashboardData(params).then(res => {
        this.dashboardData = res
      })
    }
  }
}
</script>

<style scoped lang='less'>
.research-center-payment {
  .content {
    display: flex;
    height: 520px;
    column-gap: 20px;
    .center-list {
      width: 20%;
      flex-shrink: 0;
      background-color: #FAFBFB;
      height: 100%;
      overflow-y: auto;
      &.empty {
        .ant-empty {
          padding-top: 100px;
        }
      }
      .list-item {
        height: 80px;
        padding: 16px;
        cursor: pointer;
        &.active,&:hover {
          background-color: #E7F1F7;
        }
        .item-title {
          display: flex;
          justify-content: space-between;
          .title-name {
            font-size: 16px;
            color: #000000;
          }
          .title-amount {
            color: #1890FF;
          }
        }
        .item-id {
          color: #4D5C6F;
        }
      }
    }
    .center-chart {
      width: 70%;
      flex-grow: 1;
      position: relative;
      .date-range-select {
        position: absolute;
        right: 0;
        top: 45px;
      }
    }
  }
}

</style>
